package com.tju.backend.resources.config.security.service;

import com.tju.backend.entity.SysUser;
import com.tju.backend.service.business.SysUserService;
import com.tju.backend.utils.tool.EmptyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 要实现UserDetailsService接口，这个接口是security提供的
 *
 * @USER: CLS
 */
@Service("userDetailsService")
public class AuthUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService userService;

    /**
     * 通过账号查找用户、角色的信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.getUserByUserName(username);
        if (EmptyUtils.isNotEmpty(user)) {
            //角色存储
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority(user.getRoles().getName()));
            return new AuthUser(user.getLoginName(), user.getLoginPassword(), authorities);
        } else {
            throw new UsernameNotFoundException(String.format("%s.这个用户不存在", username));
        }
    }
}
